package org.compiere.process;

import java.util.logging.Level;

import org.compiere.model.MClient;
import org.compiere.model.MMailText;
import org.compiere.model.MUser;
import org.compiere.model.X_CMS_Contract;
import org.compiere.model.X_C_BPartner;
import org.compiere.model.X_R_MailText;
import org.compiere.model.X_cms_agreement;
import org.compiere.util.DB;
import org.compiere.util.EMail;

public class CMS_InformAgreement extends SvrProcess {

	private int cms_agremeent_id = 0;

	@Override
	protected void prepare() {
		
		this.cms_agremeent_id = this.getRecord_ID();
	}

	@Override
	protected String doIt() throws Exception {
		
		X_cms_agreement agreement = new X_cms_agreement(getCtx(), cms_agremeent_id, get_TrxName());
		
		int userToID = agreement.getAD_User_ID();
		
		String sqlZerdeAdmin = "select max(ad_user_id) from ad_user where lower(name) like '%zerdea%'";
		
		int userFromID = DB.getSQLValue(get_TrxName(), sqlZerdeAdmin);
		
		if(userFromID == -1)
			throw new Exception("Ошибка получения отправителя");
		
		X_CMS_Contract contract = new X_CMS_Contract(getCtx(), agreement.getCMS_Contract_ID(), get_TrxName());
		
		String message = "Вам нужно рассмотреть для одобрения договор №" + contract.getDocumentNo() + ".\n\r";
		message += "Предмет договора - " + contract.getDescription();
		
		
		String label = "Согласование договора";
		
		try
		{
			sendMail(userToID, userFromID, label, message);
		}
		catch (Exception e)
		{
			log.log(Level.SEVERE, e.toString());
		}
		
		return "";
	}

	private boolean sendMail(int userToID, int userFromID, String label, String message) throws Exception
	{
		MUser userFrom = new MUser(getCtx(), userFromID, get_TrxName());
		MUser userTo = new MUser(getCtx(), userToID, get_TrxName());

		MClient client = new MClient(getCtx(), getAD_Client_ID(), get_TrxName());
		
		X_R_MailText rText = new X_R_MailText(getCtx(), null, get_TrxName());		
		
		StringBuffer sql = new StringBuffer();
		sql.setLength(0);
	
		sql.append("select c_bpartner_id from ad_user where ad_user_id = " + userFromID);
		int C_BPartner_ID = DB.getSQLValue(get_TrxName(), sql.toString());
		
		if(C_BPartner_ID == -1)
			throw new Exception("Ошибка получения имени отправителя");
		
		X_C_BPartner bpartner = new X_C_BPartner(getCtx(), C_BPartner_ID, get_TrxName());
		
		rText.setName(bpartner.getName());
		rText.setMailHeader(label);
		rText.setMailText(message);
		
		if(!rText.save())
			throw new Exception("Невозможно сохранить сообщение");
		
		MMailText mailText = new MMailText(getCtx(), rText.get_ID(), get_TrxName());
		
		EMail mail = client.createEMail(userFrom, userTo, mailText.getMailHeader(), mailText.getMailText());	
		
		try 
		{
			EMail.SENT_OK.equals(mail.send());
		}
		catch(Exception e)
		{
			log.log(Level.SEVERE, e.toString());
		}
		
		return true;
	}
}
